Angular / Form / Multi checkbox in a form
Multi Checkbox
-
in component
Declare FormArray for multi-checkbox
itemArray: FormArray; add itemArray to mainform group
this.mainForm = this.fb.group({ 'id': [''], 'name': ['', Validators.required], itemArray: this.fb.array([ ]) }); Define itemArray structure
createItem(item:any): FormGroup { return this.fb.group({ id:[item.id], title:[item.title], isChecked: [item.isChecked] }); } populate data to checkbox
1) Access 'itemArray' controls of mainForm Group
this.items = this.mainForm.get('itemArray') as FormArray; 2. push the value to itemArray
this.permissions.forEach(row => { this.items.push(this.createItem(row)); }); 1) Note, this.permissions is json data
2) this.permissions contains, [{id:1,title:'sun',isChecked:true}, {id:2,title:'mon',isChecked:true}]
3) variable 'row' is passed to this.createItem() for setting value -
in view
{row.get('title').value}
Note that 'itemArray' control is looped, mainForm.get('itemArray')?.controls;